package com.jeeplus.cms.support.validation;

import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义正则注解
 *
 * @author Sawyer
 * @date 2020-12-15
 */
public class PatternExtendImpl implements ConstraintValidator<PatternExtend, Object> {

    private String regexp;
    private boolean required;

    @Override
    public void initialize(PatternExtend constraintAnnotation) {
        this.regexp = constraintAnnotation.regexp();
        this.required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {

        if (required) {
            if (null == value || StringUtils.isBlank(value.toString())) {
                return false;
            }
        } else {
            // 如果值非必须,为null直接返回true.
            if (null == value || StringUtils.isBlank(value.toString())) {
                return true;
            }
        }

        //如果正则为空，则直接返回true
        if ("".equals(regexp)) {
            return true;
        }

        Pattern pattern = Pattern.compile(regexp);
        String target = String.valueOf(value);
        Matcher matcher = pattern.matcher(target);
        return matcher.matches();
    }
}
